package MD.NJavaUnionAd;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
//import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import MD.NJavaBase.AdType;
import MD.NJavaBase.IAd;
import MD.NJavaBase.IAdCallback;
import MD.NJavaBase.ICallbackLight;
//import MD.NJavaBase.Logger;
import MD.NJavaBase.NJavaBase;

public class UnionVideo implements IAd, TTAdNative.RewardVideoAdListener {
    static String Tag = "UnionVideo";

    public UnionVideo(int priority)
    {
        Log.e(Tag, "UnionVideo #1");
        m_Priority = priority;
        Activity activity = NJavaBase.getActivity();
        String videoUnitId = "";
        try {
            ApplicationInfo appInfo = activity.getPackageManager().getApplicationInfo(
                    activity.getPackageName(), PackageManager.GET_META_DATA
            );

            videoUnitId = appInfo.metaData.getString("UnionVideoid") ;
            if(videoUnitId.length()>0 && videoUnitId.charAt(0)=='#')
                videoUnitId = videoUnitId.substring(1);

            this.IsHorizontal =  appInfo.metaData.getString("UnionIsHorizontal") =="T";

        } catch (PackageManager.NameNotFoundException e) {
            Log.e(Tag, "UnionVideo init error!");
            e.printStackTrace();
        }

        Log.e(Tag, "UnionVideo #2");
        m_VideoId = videoUnitId;

        //强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdSdk.getAdManager().requestPermissionIfNecessary(activity);
        Log.e(Tag, "UnionVideo #3");
        m_AdNative = TTAdSdk.getAdManager().createAdNative(activity);
        Log.e(Tag, "UnionVideo #4");

        //等待一会儿才允许装载视频
        {
            Timer reloadTimer = new Timer();// 实例化Timer类
            class overTimeTask extends TimerTask {
                public void run() {
                    class reloadRunnable implements Runnable {
                        @Override
                        public void run() {
                            m_Initdone = true;
                        }
                    }
                    NJavaBase.getActivity().runOnUiThread(new reloadRunnable());
                    this.cancel();
                }
            }
            reloadTimer.schedule(new overTimeTask(), 5000);// 毫秒
        }
    }

    //广告类型
    public AdType getAdType()
    {
        return AdType.rewardVideo;
    }

    //是否已经初始化完毕，可以开始加载视频
    public boolean isInitialized() {return m_Initdone;}

    //广告平台的名称
    public String adName() { return "UnionVideo"; }

    //当前视频是否已经过期
    public boolean isInvalidated() { return !m_CacheOk; }

    //预装视频 回调0表示预装成功 99表示预装失败  2视频播放结束可以获得奖励 3视频已关闭
    public void reloadAd(IAdCallback callBack)
    {
        if(m_Loading ) return;
         m_Callback = callBack;
        if(!m_CacheOk)//没有缓存成功
        {
            m_Loading = true;
           
            this.load();
        }else{ //已经是装载成功的
            callBack.onLoad();
        }
    }

    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


    void load()
    {
        Log.e(Tag, "load #1");
        //Random random=new Random();
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(m_VideoId)
                .setSupportDeepLink(true)
                //.setAdCount(2)
                //.setImageAcceptedSize(1080, 1920)
                .setRewardName("金币")//.setRewardName("奖励") //奖励的名称
                .setRewardAmount(3)//.setRewardAmount(1)   //奖励的数量

                //必传参数，表来标识应用侧唯一用户；若非服务器回调模式或不需sdk透传
                //可设置为空字符串
                .setUserID("user123")//getRandomString(5+random.nextInt(5))
                .setMediaExtra("media_extra") //用户透传的信息，可不传
                .setOrientation(IsHorizontal?TTAdConstant.HORIZONTAL:TTAdConstant.VERTICAL)  //设置期望视频播放的方向，为TTAdConstant.HORIZONTAL或TTAdConstant.VERTICAL
                .build();
        m_AdNative.loadRewardVideoAd(adSlot, this);
        Log.e(Tag, "load setName");
    }

    //是否需要由loader去检查加载超时
    public boolean needCheckLoadOvertime() { return true; }

    //显示视频
    public void show()
    {

        if(m_CacheOk)//调用show之前，外部已经判断过是否装成功，如果这里返回false，应该是有问题
        {
            Log.e(Tag, "show #1");
            m_CacheOk = false;
            m_Video.showRewardVideoAd(NJavaBase.getActivity(),TTAdConstant.RitScenes.CUSTOMIZE_SCENES,"scenes_test");
        }
        else {
            Log.e(Tag, "show #2");
            this.load();//立即发起装载
        }
    }

    //优先级，值越大越优先
    public  int getPriority() { return m_Priority; }


    ////////////////////////////////////////////////////
    //视频加载回调接口
    ////////////////////////////////////////////////////
    @Override
    public void onError(int var1, String var2)
    {
        m_Loading = false;
        //返回错误信息
        m_Callback.onError(String.valueOf(-99));
        Log.e(
            Tag,
            var2==null?String.format("video load failed! code %d",var1):String.format("video load failed! code %d %s",var1,var2)
        );
    }

    @Override
    public void onRewardVideoAdLoad(TTRewardVideoAd var1)
    {
        m_Loading = false;
        Log.d(Tag, "onRewardVideoAdLoad ");
        m_Video = var1;
        m_Video.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
            @Override
            public void onVideoError()
            {
                Log.e(Tag, "onVideoError ");
                m_Callback.onClose();
            }

            @Override
            public void onSkippedVideo()
            {
                Log.e(Tag, "onSkippedVideo ");
                //通知关闭
                m_Callback.onClose();
            }

            @Override
            public void onAdShow() {
                //Toast.makeText(RewardVideoActivity.this, "rewardVideoAd show", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdVideoBarClick() {
                //Toast.makeText(RewardVideoActivity.this, "rewardVideoAd bar click", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdClose() {
                Log.e(Tag, "onAdClose ");
                //通知关闭
                m_Callback.onClose();
            }

            //视频播放完成
            @Override
            public void onVideoComplete() {
                //Toast.makeText(RewardVideoActivity.this, "rewardVideoAd complete", Toast.LENGTH_SHORT).show();

                Log.e(Tag, "onVideoComplete ");

            }

            @Override
            public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName) {
                //可获得奖励
                Log.e(Tag, "onRewardVerify ");
                //可获得奖励
                m_Callback.onReward();
            }
        });

        /*
        m_Video.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() { }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {  }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {  }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) { }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) { }

            @Override
            public void onInstalled(String fileName, String appName) {  }
        });
*/

    }

    @Override
    public void onRewardVideoCached()
    {
        Log.e(Tag, "onRewardVideoCached ");
        m_Loading = false;
        m_CacheOk = true;
        m_Callback.onLoad();
        Log.d(Tag, "onRewardVideoAdLoad#1");
    }

    ////////////////////////////////////////////////////
    //视频下载回调接口
    ////////////////////////////////////////////////////

    ////////////////////////////////////////////////////
    //视频显示及奖励回调接口
    ////////////////////////////////////////////////////


    int m_Priority;
    boolean m_Loading = false;
    boolean m_CacheOk = false;
    TTRewardVideoAd m_Video = null;
    IAdCallback m_Callback;
    String m_VideoId;//广告id
    TTAdNative m_AdNative;
    boolean IsHorizontal = false;
    boolean m_Initdone = false;
}